package com.ljb.ardemo;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.ljb.lib_ar.ArView;
import com.ljb.lib_ar.EasyAR;
import com.ljb.lib_ar.OnTargetChangeListener;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import cn.easyar.Target;


/**
 * @author ljb
 * @des AR容器Activity
 * @date 2019/11/16
 */
public class ARActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private String cacheDirPath;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ar);
        cacheDirPath = getExternalCacheDir().getPath();

        //保持屏幕常量
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        //复制文件
        copyFile();
        //请求权限
        requestCameraPermission(new PermissionCallback() {
            @Override
            public void onSuccess() {
                initAR();
            }

            @Override
            public void onFailure() {
            }
        });
    }

    private void initAR() {
        ArView arView = EasyAR.getDefault(this)
                //设置目标Target的本地路径
                .setTarget(cacheDirPath + "/json_targets.json")
                //设置发现目标后的回调
                .setOnTargetChangeListener(new OnTargetChangeListener() {
                    @Override
                    public void onTargetChange(final Target target) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Log.e(TAG, "onTargetChange: " + target.name());
                                Toast.makeText(ARActivity.this, target.name(), Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                }).create(this);
        ((ViewGroup) findViewById(R.id.preview)).addView(arView, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
    }

    private void copyFile() {
        //将资源文件复制到SD卡中
        copyAssetsToDst(this, "image_targets", cacheDirPath);
    }

    /**
     * 将Assets中的文件复制到SD卡
     *
     * @param context
     * @param srcPath
     * @param dstPath
     */
    public static void copyAssetsToDst(Context context, String srcPath, String dstPath) {
        try {
            String fileNames[] = context.getAssets().list(srcPath);

            if (fileNames.length > 0) {
                File file = new File(dstPath);
                if (!file.exists()) {
                    file.mkdirs();
                }
                for (String fileName : fileNames) {
                    // assets 文件夹下的目录
                    if (!TextUtils.isEmpty(srcPath)) {
                        copyAssetsToDst(context, srcPath + File.separator + fileName, dstPath + File.separator + fileName);
                        // assets 文件夹
                    } else {
                        copyAssetsToDst(context, fileName, dstPath + File.separator + fileName);
                    }
                }
            } else {
                File outFile = new File(dstPath);
                Log.e(TAG, "copyAssetsToDst: " + outFile.getAbsolutePath());
                InputStream is = context.getAssets().open(srcPath);
                FileOutputStream fos = new FileOutputStream(outFile);
                byte[] buffer = new byte[1024];
                int byteCount;
                while ((byteCount = is.read(buffer)) != -1) {
                    fos.write(buffer, 0, byteCount);
                }
                fos.flush();
                is.close();
                fos.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //++++++++++++++++++++++++++++++++++++++++  权限  ++++++++++++++++++++++++++++++++++++++++//

    private Map<Integer, PermissionCallback> permissionCallbacks = new HashMap<>();
    private int permissionRequestCodeSerial = 0;

    @TargetApi(23)
    private void requestCameraPermission(PermissionCallback callback) {
        if (Build.VERSION.SDK_INT >= 23) {
            if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                int requestCode = permissionRequestCodeSerial;
                permissionRequestCodeSerial += 1;
                permissionCallbacks.put(requestCode, callback);
                requestPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, requestCode);
            } else {
                callback.onSuccess();
            }
        } else {
            callback.onSuccess();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (permissionCallbacks.containsKey(requestCode)) {
            PermissionCallback callback = permissionCallbacks.get(requestCode);
            permissionCallbacks.remove(requestCode);
            boolean executed = false;
            for (int result : grantResults) {
                if (result != PackageManager.PERMISSION_GRANTED) {
                    executed = true;
                    callback.onFailure();
                }
            }
            if (!executed) {
                callback.onSuccess();
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}
